#!/bin/bash

# 证书链验证（严格匹配Deepin商店规范）
verify_cert_chain() {
  local file="$1"
  openssl pkcs7 -in "$file" -inform der -print_certs | awk '
    /CN=Deepin Store Release/ { release=1 }
    /CN=Deepin Root CA/ { root=1 }
    END {
      if (release && root) exit 0;
      else exit 1;
    }'
}

# DEB包签名验证
verify_deb() {
  if ! dpkg-sig --verify "$1" | grep -q 'GOODSIG'; then
    echo "❌ DEB签名验证失败：无效的GPG签名"
    return 1
  fi
  
  # 补充证书链验证
  if ! verify_cert_chain "$1"; then
    echo "❌ DEB证书链验证失败"
    return 1
  fi
}

# Snap包验证（签名+发布者ID）
verify_snap() {
  local pkg="$1"
  
  # 签名有效性验证
  if ! snapcraft verify "$pkg"; then
    echo "❌ Snap签名验证失败"
    return 1
  fi
  
  # 发布者ID检查（必须为deepin）
  local publisher=$(snap info "$pkg" | awk -F': ' '/publisher:/ {print $2}')
  [[ "$publisher" == "deepin" ]] || {
    echo "❌ 非官方发布者: $publisher"
    return 1
  }
}

# 玲珑包验证（结构/签名/哈希）
verify_linglong() {
  local pkg="$1"
  
  # 验证基础包结构
  if ! ll-cli inspect "$pkg" >/dev/null 2>&1; then
    echo "❌ 玲珑包结构验证失败"
    return 1
  fi

  # 检查数字签名
  local signer=$(ll-cli verify --signature "$pkg" | awk '/Signer:/ {print $2}')
  if [[ "$signer" != "DeepinStore" ]]; then
    echo "❌ 签名发布者验证失败: $signer"
    return 1
  fi

  # 校验文件哈希
  if ! ll-cli verify --checksum "$pkg"; then
    echo "❌ 文件哈希校验失败"
    return 1
  fi
}

# 统一验证入口（严格匹配图像中的蓝色分割线规范）
case "$1" in
  *.deb)
    if verify_deb "$1"; then
      echo "✅ DEB验证通过（签名+证书链）"
      exit 0
    else
      exit 1
    fi
    ;;
    
  *.uab)
    if verify_linglong "$1"; then
      echo "✅ 玲珑包验证通过（结构/签名/哈希）"
      exit 0
    else
      exit 1
    fi
    ;;
    
  *.snap)
    if verify_snap "$1"; then
      echo "✅ Snap验证通过（签名+发布者）"
      exit 0
    else
      exit 1
    fi
    ;;
    
  *)
    echo -e "\033[34m⚠️  不支持的包格式: ${1##*.}\033[0m"
    echo "支持格式:"
    echo -e "  \033[94m.deb\033[0m   - Deepin二进制包"
    echo -e "  \033[94m.uab\033[0m  - 玲珑应用包"
    echo -e "  \033[94m.snap\033[0m - Snap通用包"
    exit 2
    ;;
esac